﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using TodayWhoModel;

namespace TodayWho
{
    public partial class signup : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string state = Request.QueryString["st"];
                switch (state)
                {
                    case "2":
                        ActivateStep2();
                        //Page.Form.DefaultButton = btnGoToStep3.UniqueID;
                        break;
                    case "3":
                        ActivateStep3();
                        //Page.Form.DefaultButton = btnGoToStep4.UniqueID;
                        break;
                    case "4":
                        ActivateStep4();
                        //Page.Form.DefaultButton = btnSignup.UniqueID;
                        break;
                    case "5":
                        ActivateStep5();
                        break;
                    default:
                        ActivateStep1();
                        //Page.Form.DefaultButton = btnGoToStep2.UniqueID;
                        break;
                }

                if (Session["PhotoId"] != null)
                {
                    string tempFileName = Session["PhotoId"].ToString() + "_temp";
                    string filePath = Server.MapPath("images/tempProfilePics/" + tempFileName + ".jpg");
                    if (System.IO.File.Exists(filePath))
                    {
                        System.Drawing.Image img;
                        img = System.Drawing.Image.FromFile(filePath);
                        int originalHeight = img.Height;
                        int originalWidth = img.Width;
                        int newWidth;
                        int newHeight;
                        if (originalWidth > originalHeight)
                        {
                            newWidth = 400;
                            newHeight = originalHeight * newWidth / originalWidth;
                        }
                        else
                        {
                            newHeight = 400;
                            newWidth = originalWidth * newHeight / originalHeight;
                        }
                        tempImage.Width = newWidth;
                        tempImage.Height = newHeight;
                        tempImage.Src = "images/tempProfilePics/" + tempFileName + ".jpg";
                        preview.Src = "images/tempProfilePics/" + tempFileName + ".jpg";
                        hasImageDiv.Visible = true;
                        btnSignup.Visible = true;
                        img.Dispose();
                    }
                    else
                    {

                    }
                }
            }
        }
            
        private void ActivateStep1()
        {
            
        }
        private void ActivateStep2()
        {
            if (Session["newUserId"] == null)
            {
                Response.Redirect("signup.aspx");
            }
            else
            {
                ChangePanel(2);
            }
        }
        private void ActivateStep3()
        {
            if (Session["newUserId"] == null)
            {
                Response.Redirect("signup.aspx");
            }
            else
            {
                ChangePanel(3);
            }
        }
        private void ActivateStep4()
        {
            if (Session["newUserId"] == null)
            {
                Response.Redirect("signup.aspx");
            }
            else
            {
                ChangePanel(4);
            }
        }
        private void ActivateStep5()
        {
            if (Session["newUserId"] == null)
            {
                Response.Redirect("signup.aspx");
            }
            else
            {
                ChangePanel(5);
            }
        }

        private void ChangePanel(int step)
        {
            switch (step)
            { 
                case 1:
                    step1.Style["display"] = "block";
                    step2.Style["display"] = "none";
                    step3.Style["display"] = "none";
                    step4.Style["display"] = "none";
                    step5.Style["display"] = "none";
                    break;
                case 2:
                    step1.Style["display"] = "none";
                    step2.Style["display"] = "block";
                    step3.Style["display"] = "none";
                    step4.Style["display"] = "none";
                    step5.Style["display"] = "none";
                    break;
                case 3:
                    step1.Style["display"] = "none";
                    step2.Style["display"] = "none";
                    step3.Style["display"] = "block";
                    step4.Style["display"] = "none";
                    step5.Style["display"] = "none";
                    break;
                case 4:
                    step1.Style["display"] = "none";
                    step2.Style["display"] = "none";
                    step3.Style["display"] = "none";
                    step4.Style["display"] = "block";
                    step5.Style["display"] = "none";
                    break;
                case 5:
                    step1.Style["display"] = "none";
                    step2.Style["display"] = "none";
                    step3.Style["display"] = "none";
                    step4.Style["display"] = "none";
                    step5.Style["display"] = "block";
                    break;
                default:
                    step1.Style["display"] = "block";
                    step2.Style["display"] = "none";
                    step3.Style["display"] = "none";
                    step4.Style["display"] = "none";
                    step5.Style["display"] = "none";
                    break;
            }
        }

        protected void btnGoToStep2_OnClick(object sender, EventArgs e)
        {   
            // event when user enters mail,pass and username

            TodayWhoModel.UserModel user = new UserModel();
            user.Email = txtEmail.Text.Trim();
            user.Password = txtPassword.Text.Trim();
            user.UserName = txtUserName.Text.Trim();

            if (Helper.IsKeywordinUserName(user.UserName)) // sistemde olmamasi gereken kullanici adlarini check ediyor
            {
                lblStep1Errors.Text = "Kullanıcı adı sistemde kullaniliyor. Başka bir kullanıcı adı deneyiniz.";
                lblStep1Errors.Visible = true;
            }
            else if (!user.IsEmailUnique())
            {
                lblStep1Errors.Text = "Email adresi sistemde kullaniliyor. Başka bir email adresi deneyiniz.";
                lblStep1Errors.Visible = true;
            }
            else if (!user.IsUserNameUnique())
            {
                lblStep1Errors.Text = "Kullanıcı adı sistemde kullaniliyor. Başka bir kullanıcı adı deneyiniz.";
                lblStep1Errors.Visible = true;
            }
            else
            {
                if (user.Insert() == 0)
                {
                    lblStep1Errors.Text = "Bir hata oluştu. Lütfen daha sonra tekrar deneyiniz.";
                    lblStep1Errors.Visible = true;
                }
                else
                {
                    Session.Add("newUserId", user.UserId);
                    Mailer.SendWelcomeEmail(user.Email);
                    Response.Redirect("signup.aspx?st=2");
                }
            }

        }

        protected void btnGoToStep3_OnClick(object sender, EventArgs e)
        {   
            // event for category name and short bio
            TodayWhoModel.UserModel user = new UserModel();
            user.UserId = Convert.ToInt32(Session["newUserId"].ToString());
            user.NameSurname = txtName.Text.Trim();
            user.ShortDesc = txtDescription.Text.Trim();
            user.CategoryId = Convert.ToInt32(ddListCategory.SelectedValue);

            if (user.UpdatePersonalInfo())
            {
                Response.Redirect("signup.aspx?st=3");
            }
            else
            {
                lblStep2Errors.Text = "Bir hata oluştu. Lütfen daha sonra tekrar deneyiniz.";
                lblStep2Errors.Visible = true;
            }
            
        }

        protected void btnGoToStep4_OnClick(object sender, EventArgs e)
        {   
            // event for social network links
            TodayWhoModel.UserModel user = new UserModel();
            user.UserId = Convert.ToInt32(Session["newUserId"].ToString());
            user.Facebook = Helper.ConvertToHttpLinks(txtFacebook.Text.Trim());
            user.Twitter = Helper.ConvertToHttpLinks(txtTwitter.Text.Trim());
            user.Blogger = Helper.ConvertToHttpLinks(txtBlogger.Text.Trim());
            user.Wordpress = Helper.ConvertToHttpLinks(txtWordpress.Text.Trim());
            user.Linkedin = Helper.ConvertToHttpLinks(txtLinkedin.Text.Trim());
            user.Tumblr = Helper.ConvertToHttpLinks(txtTumblr.Text.Trim());
            user.Formspring = Helper.ConvertToHttpLinks(txtFormspring.Text.Trim());
            user.Stumbleupon = Helper.ConvertToHttpLinks(txtStumbleupon.Text.Trim());
            user.Flickr = Helper.ConvertToHttpLinks(txtFlickr.Text.Trim());
            user.Picasa = Helper.ConvertToHttpLinks(txtPicasa.Text.Trim());
            user.Myspace = Helper.ConvertToHttpLinks(txtMyspace.Text.Trim());
            user.Lastfm = Helper.ConvertToHttpLinks(txtLastfm.Text.Trim());
            user.Youtube = Helper.ConvertToHttpLinks(txtYoutube.Text.Trim());
            user.Foursquare = Helper.ConvertToHttpLinks(txtFoursquare.Text.Trim());
            user.Website1 = Helper.ConvertToHttpLinks(txtWebsite1.Text.Trim());
            user.Website2 = Helper.ConvertToHttpLinks(txtWebsite2.Text.Trim());
            user.Website3 = Helper.ConvertToHttpLinks(txtWebsite3.Text.Trim());

            if (user.UpdateSocialNetworkInfo())
            {
                Response.Redirect("signup.aspx?st=4");
            }
            else
            {
                lblStep3Errors.Text = "Bir hata oluştu. Lütfen daha sonra tekrar deneyiniz.";
                lblStep3Errors.Visible = true;
            }
        }

        protected void upload_OnClick(object sender, EventArgs e)
        {
            if (imgUpload.HasFile)
            {
                if (imgUpload.PostedFile.ContentType.Contains("image"))
                {
                    string photoID = Guid.NewGuid().ToString();
                    string tempFileName = photoID + "_temp";
                    string filepath = Server.MapPath("images/tempProfilePics/" + tempFileName + ".jpg");
                    string filepath2 = Server.MapPath("images/tempProfilePics/" + tempFileName + "_2.jpg");

                    imgUpload.SaveAs(filepath2);

                    System.Drawing.Image img;
                    img = System.Drawing.Image.FromFile(filepath2);

                    // if image ratio is not appropriate
                    if (img.Height / img.Width > 1.5 || img.Width / img.Height > 1.5) 
                    {
                        lblImageError.Visible = true;
                        img.Dispose();
                        System.IO.File.Delete(filepath2);
                    }
                    // if image size is not appropriate
                    else if (img.Height < 450 || img.Width < 450)
                    {
                        lblImageError.Text = "Lütfen daha büyük bir fotoğraf yükleyiniz.";
                        lblImageError.Visible = true;
                        img.Dispose();
                        System.IO.File.Delete(filepath2);
                    }
                    else
                    {
                        ImageHelper objHelper = new ImageHelper();
                        System.Drawing.Image imgResized = objHelper.Resize(img, 400, 400);

                        imgResized.Save(filepath);
                        img.Dispose();
                        imgResized.Dispose();
                        System.IO.File.Delete(filepath2);

                        Session.Add("PhotoId", photoID);

                        Response.Redirect("signup.aspx?st=4");
                    }   
                }
            }
        }

        protected void saveImages_Click(object sender, EventArgs e)
        {
            var x = int.Parse(_xField.Value);
            var y = int.Parse(_yField.Value);
            var width = int.Parse(_widthField.Value);
            var height = int.Parse(_heightField.Value);

            string photoID = Session["PhotoId"].ToString();
            string tempFileName = photoID + "_temp";
            string filePath = Server.MapPath("images/tempProfilePics/" + tempFileName + ".jpg");
            System.Drawing.Image img1;
            img1 = System.Drawing.Image.FromFile(filePath);
            img1.Save(Server.MapPath("images/profilePics/" + photoID + "_1.png"));
            img1.Dispose();

            using (var photo =
                System.Drawing.Image.FromFile(filePath))
            using (var result =
                new Bitmap(width, height, photo.PixelFormat))
            {
                result.SetResolution(
                        photo.HorizontalResolution,
                        photo.VerticalResolution);

                using (var g = Graphics.FromImage(result))
                {
                    g.InterpolationMode =
                        InterpolationMode.HighQualityBicubic;
                    g.DrawImage(photo,
                        new Rectangle(0, 0, width, height),
                        new Rectangle(x, y, width, height),
                        GraphicsUnit.Pixel);
                    photo.Dispose();
                    result.Save(Server.MapPath("images/profilePics/" + photoID + "_3.png"));
                    g.Dispose();
                    result.Dispose();
                }
            }
            deleteTempImages(photoID);
            System.Drawing.Image img;
            img = System.Drawing.Image.FromFile(Server.MapPath("images/profilePics/" + photoID + "_3.png"));
            if (img.Height > 175)
            {
                ImageHelper objHelper = new ImageHelper();
                System.Drawing.Image imgResizedFor175 = objHelper.Resize(img, 175, 175);
                imgResizedFor175.Save(Server.MapPath("images/profilePics/" + photoID + "_2.png"));

                /* rounded image için
                objHelper.CreateRoundedImage(Server.MapPath("images/profilePics/" + userID + "_1.png"), Server.MapPath("images/profilePics/" + userID + "_round.png"));
                */

                imgResizedFor175.Dispose();
            }
            else if (img.Height > 67)
            {
                img.Save(Server.MapPath("images/profilePics/" + photoID + "_2.png"));
            }
            else
            {
                img.Save(Server.MapPath("images/profilePics/" + photoID + "_2.png"));
            }
            img.Dispose();
            System.IO.File.Delete(Server.MapPath("images/profilePics/" + photoID + "_3.png"));


            UserModel user = new UserModel();
            user.UserId = Convert.ToInt32(Session["newUserId"].ToString());
            user.IsTherePhoto = true;
            user.PhotoUrl1 = "/images/profilePics/" + photoID + "_1.png";
            user.PhotoUrl2 = "/images/profilePics/" + photoID + "_2.png";

            if (user.UpdatePhotoInfo())
            {
                UserDisplayModel userDisplay = new UserDisplayModel();
                userDisplay.UserId = user.UserId;
                userDisplay.IsActive = true;
                userDisplay.UpdateIsActive();
                Response.Redirect("signup.aspx?st=5");
            }
            else
            {
                lblImageError.Text = "Bir hata oluştu. Lütfen daha sonra tekrar deneyiniz.";
                lblImageError.Visible = true;
            }
        }

        private void deleteTempImages(string userID)
          {
              string tempFileName = userID + "_temp";
              string filePath = Server.MapPath("images/tempProfilePics/" + tempFileName + ".jpg");
              if (System.IO.File.Exists(filePath))
              {
                  System.IO.File.Delete(filePath);
              }
              hasImageDiv.Visible = false;
          }

        protected void btnGoHome_OnClick(object sender, EventArgs e)
        {
            Response.Redirect("home.aspx");
        }
      
    }
}